<template>
	<view class="consultation-page">
		<!-- 顶部标题栏 -->
		<view class="header">
			<view class="header-content">
				<view class="title">智能咨询</view>
				<view class="subtitle">专业心理咨询，随时为您服务</view>
			</view>
			<view class="new-btn" @click="createConsultation">
				<text class="iconfont icon-add"></text>
			</view>
		</view>

		<!-- 咨询列表 -->
		<scroll-view class="consultation-list" scroll-y refresher-enabled @refresherrefresh="onRefresh" :refresher-triggered="refreshing">
			<!-- 空状态 -->
			<view v-if="consultationList.length === 0 && !loading" class="empty-state">
				<image class="empty-image" src="../../static/img/noPeple.png" mode="aspectFit"></image>
				<view class="empty-title">还没有咨询记录</view>
				<view class="empty-subtitle">点击右上角"+"开始您的第一次智能咨询</view>
				<view class="empty-btn btn-primary" @click="createConsultation">开始咨询</view>
			</view>

			<!-- 咨询列表 -->
			<view v-else>
				<view 
					v-for="(item, index) in consultationList" 
					:key="item.id"
					class="consultation-item"
					@click="enterConsultation(item)"
					@touchstart="onTouchStart($event, index)"
					@touchmove="onTouchMove($event, index)"
					@touchend="onTouchEnd($event, index)"
					:style="{ transform: `translateX(-${item.deleteOffset || 0}rpx)` }"
				>
					<view class="item-content">
						<view class="avatar-section">
							<image class="avatar avatar-md" :src="item.avatar || '../../static/img/ai_avatar.png'"></image>
							<view v-if="item.unreadCount > 0" class="unread-badge">
								{{ item.unreadCount > 99 ? '99+' : item.unreadCount }}
							</view>
						</view>
						
						<view class="content-section">
							<view class="consultation-title">{{ item.title || '智能咨询师' }}</view>
							<view class="last-message">{{ item.lastMessage || '开始您的智能咨询吧' }}</view>
							<view class="time">{{ formatTime(item.lastTime) }}</view>
						</view>
					</view>
					
					<!-- 删除按钮 -->
					<view class="delete-btn" @click.stop="deleteConsultation(item)">
						<text class="iconfont icon-delete"></text>
						<text>删除</text>
					</view>
				</view>
			</view>

			<!-- 加载状态 -->
			<view v-if="loading" class="loading-state">
				<text class="loading-text">加载中...</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			loading: false,
			refreshing: false,
			touchStartX: 0,
			deleteOffset: 0,
			maxDeleteOffset: 120,
			isDataReady: false // 标记数据是否已准备就绪
		}
	},
	computed: {
		consultationList() {
			return this.$store.state.consultation.list;
		}
	},
	onShow() {
		this.loadConsultationList();
	},
	methods: {
		// 加载咨询列表
		async loadConsultationList() {
			if (this.loading) return;
			
			this.loading = true;
			try {
				await this.$store.dispatch('consultation/fetchList');
				this.isDataReady = true;
				
				// 确保DOM更新完成后，事件绑定才生效
				this.$nextTick(() => {
					console.log('咨询列表数据加载完成，DOM已更新');
				});
			} catch (error) {
				console.error('加载咨询列表失败:', error);
				this.showError('加载失败，请重试');
			} finally {
				this.loading = false;
			}
		},

		// 下拉刷新
		async onRefresh() {
			this.refreshing = true;
			try {
				await this.loadConsultationList();
			} finally {
				this.refreshing = false;
			}
		},

		// 创建新咨询
		async createConsultation() {
			uni.showLoading({ title: '创建中...', mask: true });
			
			try {
				const consultation = await this.$store.dispatch('consultation/create');
				uni.hideLoading();
				
				// 跳转到聊天页面
				uni.navigateTo({
					url: `/pages/chat/chat?consultationId=${consultation.id}`
				});
			} catch (error) {
				uni.hideLoading();
				console.error('创建咨询失败:', error);
				this.showError('创建咨询失败，请重试');
			}
		},

		// 进入咨询对话
		enterConsultation(consultation) {
			uni.navigateTo({
				url: `/pages/chat/chat?consultationId=${consultation.id}`
			});
		},

		// 删除咨询
		deleteConsultation(consultation) {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这个咨询会话吗？删除后无法恢复。',
				confirmColor: '#ff4757',
				success: async (res) => {
					if (res.confirm) {
						try {
							await this.$store.dispatch('consultation/delete', consultation.id);
							this.showSuccess('删除成功');
						} catch (error) {
							console.error('删除咨询失败:', error);
							this.showError('删除失败，请重试');
						}
					}
				}
			});
		},

		// 触摸事件处理
		onTouchStart(e, index) {
			this.touchStartX = e.touches[0].clientX;
			// 重置其他项的偏移
			this.consultationList.forEach((item, i) => {
				if (i !== index) {
					this.$set(item, 'deleteOffset', 0);
				}
			});
		},

		onTouchMove(e, index) {
			const currentX = e.touches[0].clientX;
			const diffX = this.touchStartX - currentX;
			
			if (diffX > 0) {
				const offset = Math.min(diffX, this.maxDeleteOffset);
				this.$set(this.consultationList[index], 'deleteOffset', offset);
			} else {
				this.$set(this.consultationList[index], 'deleteOffset', 0);
			}
		},

		onTouchEnd(e, index) {
			const item = this.consultationList[index];
			const offset = item.deleteOffset || 0;
			
			if (offset > this.maxDeleteOffset / 2) {
				this.$set(item, 'deleteOffset', this.maxDeleteOffset);
			} else {
				this.$set(item, 'deleteOffset', 0);
			}
		},

		// 格式化时间
		formatTime(timeStr) {
			if (!timeStr) return '';
			
			const date = new Date(timeStr);
			const now = new Date();
			const diff = now - date;
			
			if (diff < 60 * 1000) {
				return '刚刚';
			} else if (diff < 60 * 60 * 1000) {
				return `${Math.floor(diff / (60 * 1000))}分钟前`;
			} else if (diff < 24 * 60 * 60 * 1000) {
				return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
			} else if (diff < 7 * 24 * 60 * 60 * 1000) {
				const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
				return days[date.getDay()];
			} else {
				return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' });
			}
		},

		// 显示成功消息
		showSuccess(message) {
			uni.showToast({
				title: message,
				icon: 'success'
			});
		},

		// 显示错误消息
		showError(message) {
			uni.showToast({
				title: message,
				icon: 'none'
			});
		}
	}
}
</script>

<style scoped lang="scss">
.consultation-page {
	height: 100vh;
	background: #f5f5f5;
	display: flex;
	flex-direction: column;
}

.header {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	padding: 60rpx 40rpx 40rpx;
	display: flex;
	justify-content: space-between;
	align-items: flex-end;
	color: white;

	.header-content {
		flex: 1;

		.title {
			font-size: 48rpx;
			font-weight: 600;
			margin-bottom: 10rpx;
		}

		.subtitle {
			font-size: 28rpx;
			opacity: 0.9;
		}
	}

	.new-btn {
		width: 80rpx;
		height: 80rpx;
		background: rgba(255, 255, 255, 0.2);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		backdrop-filter: blur(10rpx);

		.iconfont {
			font-size: 40rpx;
		}
	}
}

.consultation-list {
	flex: 1;
	padding: 20rpx 0;
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 120rpx 40rpx;
	text-align: center;

	.empty-image {
		width: 300rpx;
		height: 300rpx;
		margin-bottom: 40rpx;
		opacity: 0.6;
	}

	.empty-title {
		font-size: 32rpx;
		color: #333;
		margin-bottom: 20rpx;
		font-weight: 500;
	}

	.empty-subtitle {
		font-size: 28rpx;
		color: #999;
		margin-bottom: 60rpx;
		line-height: 1.5;
	}

	.empty-btn {
		padding: 24rpx 60rpx;
		font-size: 30rpx;
	}
}

.consultation-item {
	position: relative;
	background: white;
	margin: 0 20rpx 20rpx;
	border-radius: 20rpx;
	overflow: hidden;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
	transition: transform 0.3s ease;

	.item-content {
		display: flex;
		padding: 30rpx;
		align-items: center;
	}

	.avatar-section {
		position: relative;
		margin-right: 30rpx;

		.unread-badge {
			position: absolute;
			top: -10rpx;
			right: -10rpx;
			background: #ff4757;
			color: white;
			font-size: 20rpx;
			padding: 6rpx 10rpx;
			border-radius: 20rpx;
			min-width: 32rpx;
			text-align: center;
			line-height: 1;
		}
	}

	.content-section {
		flex: 1;
		min-width: 0;

		.consultation-title {
			font-size: 32rpx;
			font-weight: 500;
			color: #333;
			margin-bottom: 10rpx;
		}

		.last-message {
			font-size: 28rpx;
			color: #666;
			margin-bottom: 10rpx;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}

		.time {
			font-size: 24rpx;
			color: #999;
		}
	}

	.delete-btn {
		position: absolute;
		right: -120rpx;
		top: 0;
		bottom: 0;
		width: 120rpx;
		background: #ff4757;
		color: white;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		font-size: 24rpx;

		.iconfont {
			font-size: 32rpx;
			margin-bottom: 8rpx;
		}
	}
}

.loading-state {
	display: flex;
	justify-content: center;
	padding: 40rpx;

	.loading-text {
		color: #999;
		font-size: 28rpx;
	}
}
</style>